//========================================================================
// *作者：海盗猫  主页：ilplay.com
// *脚本：UIEntityEntry
// *描述：UI实例入口脚本
// *?2021 MYJL . All rights reserved.
//* ======================================================================
using System;
using System.Collections.Generic;
using HDMCode.Hotfix;
using UnityEngine;
using UnityEngine.Events;

namespace HDMCode.UIFrame 
{
    public class RecordUI
    {
        public IUIFrameComponent Component;
        public UIEntity UI;
    }

    public class UIEntityEntry
    {
        /// <summary>
        /// 当前管理的所有UI对象
        /// </summary>
        protected Dictionary<string,UIEntity> m_AllUI { get; set; }

        /// <summary>
        /// 记录上一次处理的UI
        /// </summary>
        protected RecordUI m_RecordLastUI;

        /// <summary>
        /// 记录正在处理的UI
        /// </summary>
        protected RecordUI m_RecordCurUI;
        
        /// <summary>
        /// 用于处理释放的事件
        /// </summary>
        public UnityEvent OnRelease = new UnityEvent();
        
        /// <summary>
        /// 将UI附加到行为管理中
        /// </summary>
        /// <param name="component">返回当前组件</param>
        /// <param name="name">UI名称</param>
        /// <returns></returns>
        public (UIEntity,T) AddToUIBehavior<T>(ref T component,string name) where T : IUIFrameComponent, new()
        {
            m_AllUI ??= new();
            
            if (m_AllUI.TryGetValue(name ,out var ui))
            {
                component = new T();
                component.SetComponents(ui.UIDisplay.components);
                ui.UIFrameComponent = component;
                return (ui,component);
            }
            else
            {
                UIEntity newUI = new(name);
                component = new T();
                component.SetComponents(newUI.UIDisplay.components);
                m_AllUI.Add(name,newUI);
                newUI.UIFrameComponent = component;
                return (newUI,component);
            }
        }

        /// <summary>
        /// 从缓存中移除
        /// </summary>
        internal void RemoveToCache(string name)
        {
            m_AllUI ??= new();
            if (m_AllUI.ContainsKey(name))
                m_AllUI.Remove(name);
        }

        /// <summary>
        /// 获取UI是否已经加载
        /// </summary>
        /// <param name="name"></param>
        public bool IsLoadUI(string name)
        {
            return m_AllUI.ContainsKey(name);
        }

        /// <summary>
        /// 获取UI是否正在显示
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool IsShowUI(string name)
        {
            if (m_AllUI.TryGetValue(name, out var ui))
                return ui.IsOn();
            else
                return false;
        }

        /// <summary>
        /// 释放所有UI
        /// </summary>
        public void ReleaseAllUI()=>OnRelease?.Invoke();
    }
}


